﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Reflection;
using System.Drawing;
using System.Text;
using System.IO;
using System.Xml;
using System.Windows.Forms;
using ILog = log4net.ILog;
using log4net;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ZJGIS.EngineControl;
using DevComponents.DotNetBar;
using ZJGIS.ADF.BaseClasses;
using ZJGIS.ManageUser;
using ZJGIS.Framework;
using ESRI.ArcGIS.SystemUI;

namespace RunApplication
{
    public partial class MainFramework : Form
    {
        #region User Define
        private readonly string layoutFile = Application.StartupPath + "\\layout.config";
        private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        IApplication pApplication = new ApplicationClass();
        private const int WM_ENTERSIZEMOVE = 0x231;
        private const int WM_EXITSIZEMOVE = 0x232;
        private ZJGIS.EngineControl.PagedGrid pagedGrid1;
        private ZJGIS.EngineControl.LogPanel logPanel1;
        private ZJGIS.EngineControl.ResTree resTree1;
        private ZJGIS.EngineControl.OverViewPanel overViewPanel1;
        private ZJGIS.EngineControl.CustomTOCControl customTOCControl1;

        Timer timer = new Timer();
        //private ZJGIS.EngineControl.ContentControl contentControl1;
        ICommandPoolEx m_CommandPoolEx = new CommandPoolExClass();
        #endregion

        public MainFramework()
        {
            InitializeComponent();
        }

        void MainFramework_Load(object sender1, System.EventArgs e1)
        {
            try
            {
                #region 控件初始化
                this.SuspendLayout();
                // 
                // customTOCControl1
                // 
                this.customTOCControl1 = new ZJGIS.EngineControl.CustomTOCControl();
                this.customTOCControl1.Dock = System.Windows.Forms.DockStyle.Fill;
                this.customTOCControl1.Location = new System.Drawing.Point(0, 0);
                this.customTOCControl1.Name = "customTOCControl1";
                this.customTOCControl1.Size = new System.Drawing.Size(251, 522);
                this.customTOCControl1.TabIndex = 0;
                this.panelDockContainer1.Controls.Add(this.customTOCControl1);

                // 
                // contentControl1
                // 
                //this.contentControl1 = new ZJGIS.EngineControl.ContentControl();
                //this.contentControl1.Dock = System.Windows.Forms.DockStyle.Fill;
                //this.contentControl1.Location = new System.Drawing.Point(0, 0);
                //this.contentControl1.Name = "contentControl1";
                //this.contentControl1.Size = new System.Drawing.Size(998, 624);
                //this.contentControl1.TabIndex = 0;
                //this.panelDockContainer2.Controls.Add(this.contentControl1);


                // 
                // pagedGrid1
                // 
                this.pagedGrid1 = new ZJGIS.EngineControl.PagedGrid();
                this.pagedGrid1.DataQuery = null;
                this.pagedGrid1.DataUpdate = null;
                this.pagedGrid1.Dock = System.Windows.Forms.DockStyle.Fill;
                this.pagedGrid1.Location = new System.Drawing.Point(0, 0);
                this.pagedGrid1.Name = "pagedGrid1";
                this.pagedGrid1.RowClick = null;
                this.pagedGrid1.RowDblClick = null;
                this.pagedGrid1.Size = new System.Drawing.Size(998, 191);
                this.pagedGrid1.TabIndex = 1;
                this.pagedGrid1.Turnpage = null;
                this.panelDockContainer3.Controls.Add(this.pagedGrid1);


                // 
                // logPanel1
                // 
                this.logPanel1 = new ZJGIS.EngineControl.LogPanel();
                this.logPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
                this.logPanel1.Location = new System.Drawing.Point(0, 0);
                this.logPanel1.M_saveLog = null;
                this.logPanel1.Name = "logPanel1";
                this.logPanel1.Size = new System.Drawing.Size(998, 191);
                this.logPanel1.TabIndex = 1;
                this.panelDockContainer6.Controls.Add(this.logPanel1);

                // 
                // resTree1
                // 
                this.resTree1 = new ZJGIS.EngineControl.ResTree();
                this.resTree1.Dock = System.Windows.Forms.DockStyle.Fill;
                this.resTree1.Location = new System.Drawing.Point(0, 0);
                this.resTree1.Name = "resTree1";
                this.resTree1.Size = new System.Drawing.Size(251, 522);
                this.resTree1.TabIndex = 0;
                this.panelDockContainer5.Controls.Add(this.resTree1);

                // 
                // overViewPanel1
                // 
                this.overViewPanel1 = new ZJGIS.EngineControl.OverViewPanel();
                this.overViewPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
                this.overViewPanel1.Location = new System.Drawing.Point(0, 0);
                this.overViewPanel1.MapControl = null;
                this.overViewPanel1.Name = "overViewPanel1";
                this.overViewPanel1.Size = new System.Drawing.Size(251, 273);
                this.overViewPanel1.TabIndex = 0;
                this.panelDockContainer4.Controls.Add(this.overViewPanel1);
                #endregion

                (pApplication as IFramework).User = User.GetUser("aaa");
                (pApplication as IFramework).DockManager.DockManager = this.dotNetBarManager1;
                (pApplication as IFramework).BarManager.OnAddBarEvent += new OnAddBarEventHandler(BarManager_OnAddBarEvent);
                (pApplication as IFramework).BarManager.OnItemClickEvent += new OnItemClickEventHandler(BarManager_OnItemClickEvent);
                (pApplication as IFramework).BarManager.CreateBar((pApplication as IFramework).User);
                (pApplication as IFramework).MdiForm = this;

                this.Controls.Add(pApplication.StatusBar.StatusBar);
                this.customTOCControl1.Applicatoin = pApplication;
                this.tabControl1.SelectedTabChanged += new TabStrip.SelectedTabChangedEventHandler(tabControl1_SelectedTabChanged);
                (pApplication as IFramework).TOCControl = this.customTOCControl1.TOCControl.Object as ITOCControl;
                (pApplication as IFramework).BindControls(this.m_MapControl.Object as IMapControl3, this.m_PageLayoutControl.Object as IPageLayoutControl2, true);

                overViewPanel1.MapControl = this.m_MapControl.Object as IMapControl3;

                m_MapControl.OnBeforeScreenDraw += delegate { ShowWorkingStatus(true, -1); };
                m_MapControl.OnAfterScreenDraw += delegate { ShowWorkingStatus(false, -1); };
                m_MapControl.OnMouseMove += delegate(object sender, IMapControlEvents2_OnMouseMoveEvent e)
                {
                    SetCurrentCoords(string.Format("X:{0:F}  ,  Y:{1:F}   " + Convertor.esriUnit2Chinese(m_MapControl.MapUnits),
                                      Math.Round(e.mapX, 2), Math.Round(e.mapY, 2)));
                };

                #region ResTree
                this.resTree1.InitResourceTree(((pApplication as IFramework).User as User).UserResource);
                this.resTree1.Application = pApplication;
                this.resTree1.Dock = DockStyle.Fill;
                this.resTree1.AllowDrop = true;

                this.resTree1.OpenProject = delegate(string mxdfile)
                                 {
                                     if (mxdfile.ToLower().EndsWith("mxd"))
                                     {
                                         pApplication.OpenDocument(mxdfile);
                                     }
                                 };
                this.resTree1.AddLayers = (pApplication as IFramework).AddLayersToMapControl;
                this.resTree1.RemoveLayers = (pApplication as IFramework).RemoveLayersFromMapControl;
                this.resTree1.VisibleLayers = (pApplication as IFramework).VisibleLayersFromMapControl;
                this.resTree1.UnVisibleLayers = (pApplication as IFramework).UnVisibleLayersFromMapControl;
                #endregion

                this.ResumeLayout(true);
                (pApplication as IFramework).BarManager.CommandPoolEx.Hook = pApplication;

                #region LayoutFile
                if (File.Exists(layoutFile))
                {
                    DateTime sysUpdateTime = new FileInfo(Assembly.GetEntryAssembly().Location).LastWriteTime;
                    DateTime layoutFileUpdateTime = new FileInfo(layoutFile).LastWriteTime;
                    if (sysUpdateTime > layoutFileUpdateTime)
                    {
                        File.Delete(layoutFile);
                    }
                    else
                    {
                        try
                        {
                            LoadLayout(layoutFile);
                        }
                        catch (Exception ex)
                        {
                            log.Warn(ex.Message);
                            log.Warn(ex.StackTrace);
                        }
                        finally
                        {

                        }
                    }
                }
                #endregion

                #region 更新状态
                timer.Tick += delegate(object sender, EventArgs e)
                {
                    timer.Stop();
                    (pApplication as IFramework).BarManager.CommandPoolEx.UpdateCommandState();
                    timer.Start();
                };
                timer.Interval = 500;
                timer.Start();
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void BarManager_OnItemClickEvent(object obj)
        {
            (pApplication as IFramework).ExecuteCommand(obj as ICommand);
        }

        void BarManager_OnAddBarEvent(Bar m_Bar)
        {
            this.dockSite7.Controls.Add(m_Bar);
        }

        protected override void OnNotifyMessage(System.Windows.Forms.Message m)
        {
            base.OnNotifyMessage(m);
            if (m.Msg == WM_ENTERSIZEMOVE)
            {
                m_MapControl.SuppressResizeDrawing(true, 0);
            }
            else if (m.Msg == WM_EXITSIZEMOVE)
            {
                m_MapControl.SuppressResizeDrawing(false, 0);
            }
        }

        public void SetCurrentCoords(string text)
        {
            pApplication.StatusBar.Coordinate.Text = text;
        }

        public void ShowWorkingStatus(bool isWorking, double ratio)
        {
            if (isWorking)
                timer.Stop();
            else
                timer.Start();
            ProgressBarItem m_Progress = pApplication.StatusBar.Progress;
            if (isWorking)
            {
                m_Progress.Width = 200;
                m_Progress.Visible = true;
                Application.DoEvents();
                if (ratio < -0.99999 && ratio > -1.00001)    //ration为-1时
                {
                    m_Progress.ChunkColor = Color.FromArgb(((int)(((byte)(59)))), ((int)(((byte)(97)))), ((int)(((byte)(156)))));
                    m_Progress.ChunkColor2 = Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(207)))), ((int)(((byte)(139)))));
                    m_Progress.ChunkGradientAngle = 90F;
                    m_Progress.ProgressType = eProgressItemType.Marquee;
                }
                else
                {
                    m_Progress.ProgressType = eProgressItemType.Standard;
                    m_Progress.ColorTable = eProgressBarItemColor.Normal;
                    m_Progress.BeginGroup = true;
                    int value = Convert.ToInt32(ratio * 100);
                    m_Progress.Value = value;
                    Application.DoEvents();
                }
            }
            if (!isWorking)
            {
                m_Progress.Width = 0;
                m_Progress.Visible = false;
                Application.DoEvents();
            }
        }

        #region TabChanged
        private void tabControl1_SelectedTabChanged(object sender, TabStripTabChangedEventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            if (this.tabControl1.SelectedTab.Text == "数据视图")
                (pApplication as IFramework).ActivateMapControl();
            else if (this.tabControl1.SelectedTab.Text == "版面视图")
                (pApplication as IFramework).ActivatePageLayoutControl();
            this.Cursor = Cursors.Default;
        }
        #endregion

        #region EnterCustomize
        private void dotNetBarManager1_EnterCustomize(object sender, EventArgs e)
        {
            try
            {
                MenuCustom customMenu = new MenuCustom();
                DialogResult result = customMenu.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    dotNetBarManager1.SaveLayout(layoutFile);
                }
                else if (result == DialogResult.Yes)
                {
                    if (File.Exists(layoutFile))
                    {
                        try
                        {
                            LoadLayout(layoutFile);
                        }
                        catch (Exception ex)
                        {
                            log.Error("加载布局文件出错！", ex);
                        }
                    }
                }
                dotNetBarManager1.CustomizeClosing();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadLayout(string filepath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filepath);
            XmlNode node = xmlDoc.SelectSingleNode("//bars");
            dotNetBarManager1.ToolbarTopDockSite.LoadLayout(node as XmlElement);
            for (int i = dotNetBarManager1.Bars.Count - 1; i >= 0; i--)
            {
                Bar bar = dotNetBarManager1.Bars[i];
                if (bar.Items.Count == 0)
                {
                    bar.Hide();
                }
            }
        }
        #endregion

        #region OnFormClosing
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (e.Cancel == true) return;
            if (MessageBox.Show("您确定要退出系统吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    base.OnFormClosing(e);
                    if (e.Cancel == false)
                    {
                        dotNetBarManager1.SaveLayout(layoutFile);
                        m_MapControl.OnBeforeScreenDraw -= delegate { ShowWorkingStatus(true, -1); };
                        m_MapControl.OnAfterScreenDraw -= delegate { ShowWorkingStatus(false, -1); };
                        pApplication.Shutdown();
                        Dispose();
                    }
                }
                catch (Exception ex)
                {
                    log.Warn(ex.Message);
                    log.Warn(ex.StackTrace);
                }
            }
            else
            {
                e.Cancel = true;
            }
        }
        #endregion
    }
}

#region ButtonClick
//private void buttonItem2_Click(object sender, EventArgs e)
//{
//    pApplication.StatusBar.ShowProgressAnimation("ssss", "");
//}

//private void buttonItem3_Click(object sender, EventArgs e)
//{
//    pApplication.StatusBar.HideProgressAnimation();
//}

//private void buttonItem4_Click(object sender, EventArgs e)
//{
//    pApplication.StatusBar.PlayProgressAnimation(false);

//}

//private void buttonItem5_Click(object sender, EventArgs e)
//{
//    Control pControl = (pApplication as IFramework).DockManager.GetControlFromDockPanel("日志");
//    Control pControl1 = (pApplication as IFramework).DockManager.GetControlFromDockPanel("列表");
//}

//private void buttonItem6_Click(object sender, EventArgs e)
//{
//    (pApplication as IFramework).DockManager.ActivateDockPanel("测试");
//}

//private void buttonItem7_Click(object sender, EventArgs e)
//{
//    pApplication.StatusBar.set_Message(0, "sss测试");
//}
//private void buttonItem8_Click(object sender, EventArgs e)
//{
//    try
//    {
//        int count = (pApplication as IFramework).BarManager.CommandPoolEx.Count;
//        (pApplication as IFramework).BarManager.CommandPoolEx.Hook = pApplication;

//        (pApplication as IFramework).BarManager.CommandPoolEx.UpdateCommandState();
//        ICommandPoolEx pCommandPoolEx=(pApplication as IFramework).BarManager.CommandPoolEx;


//        //Control c = (pApplication as IFramework).DockManager.GetControlFromDockPanel("日志");
//        //LogPanel pLogPanel = this.FindLogPanelControl(c);
//        //if (pLogPanel != null)
//        //{
//        //    pLogPanel.Log("测试");
//        //}
//        //MessageBox.Show((pApplication as IFramework).BarManager.CommandPoolEx.Hook.ToString());
//    }
//    catch (Exception ex)
//    {
//        MessageBox.Show(ex.Message);
//    }
//}

//private ZJGIS.EngineControl.LogPanel FindLogPanelControl(Control c)
//{
//    if (c is ZJGIS.EngineControl.LogPanel)
//        return c as ZJGIS.EngineControl.LogPanel;
//    else
//    {
//        foreach (Control c1 in c.Controls)
//        {
//            return FindLogPanelControl(c1);
//        }
//    }
//    return null;
//}       

//private void buttonItem9_Click(object sender, EventArgs e)
//{
//    pApplication.SaveDocument(null);
//}

//private void buttonItem10_Click(object sender, EventArgs e)
//{
//    SaveFileDialog pDialog = new SaveFileDialog();
//    if (pDialog.ShowDialog() == DialogResult.OK)
//    {
//        pApplication.SaveAsDocument(pDialog.FileName, true);
//    }
//}
#endregion